/* Copyright 2007 Sergejs Melderis (sergey.melderis@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
*/

package com.sm.binder;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.ResultSetMetaData;
import java.lang.reflect.Constructor;



/**
 * Creates an instance of T using values from ResultSet as constructor arguments if any.
 *
 * @author @author Sergejs Melderis (sergey.melderis@gmail.com)
 */
interface InstanceCreator<T> {
    public T create(ResultSet rs) throws SQLException;
}



class NoArgsInstanceCreator<T> implements InstanceCreator<T> {
    private final Class<T> type;
    public NoArgsInstanceCreator(Class<T> type) {
        this.type = type;
    }

    public T create(ResultSet rs) throws SQLException{
        T t;
        try {
            t = type.newInstance();
        } catch (Exception e) {
            throw new SQLException(e.getMessage());
        }
        return t;
    }
}



class WithArgsInstanceCreator<T> implements InstanceCreator<T> {
    private final Constructor<T> constructor;
    private final ColumnValueGetter[] getters;

    public WithArgsInstanceCreator(Constructor<T> constructor, ColumnValueGetter [] getters) {
        this.constructor = constructor;
        this.getters = getters;
    }

    public T create(ResultSet rs) throws SQLException {
        Object [] args = new Object[getters.length];
        int i = 0;
        try {
            for (; i < getters.length; i++) {
                args[i] = getters[i].getValue(rs);
            }
        
            return constructor.newInstance(args);
        } catch (IllegalArgumentException e) {
            throw new SQLException(e.getMessage());
        } catch (Exception e) {
            throw new SQLException(e.getMessage());
        }
    }
}

